import logging
import dashscope
from dashscope.audio.tts_v2 import SpeechSynthesizer
import tempfile
import os
from config.config import TTS_API_KEY, TTS_MODEL, TTS_VOICE
import subprocess
import time

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class AudioService:
    def __init__(self):
        """初始化阿里云TTS服务"""
        try:
            # 手动设置API Key
            dashscope.api_key = TTS_API_KEY
            self.model = TTS_MODEL
            self.voice = TTS_VOICE
            logger.info(f"TTS服务初始化完成，模型: {self.model}, 音色: {self.voice}")
        except Exception as e:
            logger.error(f"TTS服务初始化失败: {str(e)}")
            self.initialized = False
        else:
            self.initialized = True

    def speak(self, text):
        """
        使用阿里云百炼TTS生成语音并播放
        """
        if not self.initialized:
            logger.error("TTS服务未初始化，无法生成语音")
            return False

        temp_audio_path = None
        try:
            # 1. 生成语音
            logger.info("正在生成语音")
            start_time = time.time()

            # 创建语音合成器
            synthesizer = SpeechSynthesizer(model=self.model, voice=self.voice)

            # 生成音频
            result = synthesizer.call(text)

            # 检查音频是否有效
            if not result:
                logger.error("语音生成失败，返回空结果")
                return False

            # 记录生成耗时
            generation_time = time.time() - start_time
            logger.info(f"语音生成耗时: {generation_time:.2f}秒")

            # 2. 保存到临时文件
            with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as temp_audio:
                temp_audio_path = temp_audio.name

                # 写入音频数据
                temp_audio.write(result)
                logger.info(f"语音已保存到临时文件: {temp_audio_path}")

            # 3. 使用mplayer播放
            logger.info("使用mplayer播放...")
            try:
                subprocess.run(['mplayer', temp_audio_path], check=True, capture_output=True)
                logger.info("播放完成")
                return True
            except FileNotFoundError:
                logger.error("mplayer未找到，请确保已安装")
                return False
            except subprocess.CalledProcessError as e:
                logger.error(f"播放失败: {e.stderr.decode()}")
                return False

        except dashscope.ApiException as e:
            # 处理API异常
            logger.error(f"阿里云API错误: {e.code} - {e.message}")
            return False
        except Exception as e:
            logger.error(f"语音处理异常: {str(e)}")
            return False
        finally:
            # 清理临时文件
            if temp_audio_path and os.path.exists(temp_audio_path):
                try:
                    os.remove(temp_audio_path)
                    logger.info(f"已清理临时文件: {temp_audio_path}")
                except Exception as e:
                    logger.error(f"临时文件清理失败: {e}")